package com.jmall.admin.controller;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.WebRequest;

import com.jmall.admin.service.RbacService;
import com.jmall.base.UserException;
import com.jmall.user.service.UserService;



@Controller
@RequestMapping("/adminuser")
public class UsersController {
	@Resource(name="userService")
	private UserService usersService  = null;
	@Resource(name="rbacService")
	private RbacService rbacService = null;
	
	@RequestMapping("/login")
	public String login(String username , String password , WebRequest wr){
		//利用用户名与密码令牌传递用户名密码
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		//获得消息主题
		Subject subject = SecurityUtils.getSubject(); 
				
		try {
			//调用login()方法,shiro将利用Realm与凭证匹配器校验用户与密码
			//成功继续执行,失败抛出异常跳转到Catch
			subject.login(token);
			if(subject.isAuthenticated()){ //必须经过认证才可执行下面的代码
				//当前登录人的信息
				Map user = usersService.checkLogin(username, password);
				//当前用户所拥有的角色
				List<Map> roles = rbacService.findRolesByEmp((Integer)user.get("emp_id"));
				//获取当前登录人拥有的角色编号
				List<Integer> paramRoles = new ArrayList();
				for(Map role : roles){
					paramRoles.add((Integer)role.get("role_id"));
				}
				/*
				List roles = new ArrayList();
				roles.add(2);
				roles.add(3);*/
				//查询指定拥有拥有角色能访问的模块
				List<Map> modules = rbacService.findModules(paramRoles);
				Map functionMP = new LinkedHashMap();
				//查询指定拥有拥有角色能访问的功能
				for(Map m : modules){
					//查询指定模块下的功能
					List<Map> functions = rbacService.findFunctions(paramRoles , (Integer)m.get("module_id"));
					functionMP.put("M" + m.get("module_id"), functions);
				}
				//将当前登录人的信息存放在Session.loginuser属性中
				wr.setAttribute("loginuser", user, WebRequest.SCOPE_SESSION);
				wr.setAttribute("modules", modules, WebRequest.SCOPE_REQUEST);
				wr.setAttribute("functions", functionMP, WebRequest.SCOPE_REQUEST);
				return "/admin/index.jsp";
			}else{
				return "/admin/login.jsp";
			}
		} catch (UserException e) {
			// TODO Auto-generated catch block
			//request.setAttribute("error_messager", e.getMessage());
			wr.setAttribute("error_message", e.getMessage(), WebRequest.SCOPE_REQUEST);
			return "/admin/login.jsp";
		}
	}
	
	@RequestMapping("/logout")
	public String login(WebRequest wr , HttpSession session){
		Subject subject = SecurityUtils.getSubject(); 
		subject.logout();
		return "/admin/login.jsp";
	}
}